<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
            v-model="queryParams.title"
            placeholder="请输入标题"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="概要" prop="outline">
        <el-input
            v-model="queryParams.outline"
            placeholder="请输入概要"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="负责人" prop="responsiblePerson">
        <el-input
            v-model="queryParams.responsiblePerson"
            placeholder="请输入负责人"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:activity:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:activity:edit']"
        >修改
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--            type="danger"-->
      <!--            plain-->
      <!--            icon="Delete"-->
      <!--            :disabled="multiple"-->
      <!--            @click="handleDelete"-->
      <!--            v-hasPermi="['system:activity:remove']"-->
      <!--        >删除-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:activity:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="activityList" @selection-change="handleSelectionChange">
      <!--      <el-table-column type="selection" width="55" align="center"/>-->
      <!--      <el-table-column label="主键" align="center" prop="id"/>-->
      <el-table-column show-overflow-tooltip label="标题" align="center" prop="title" width="200"/>
      <el-table-column show-overflow-tooltip label="概要" align="center" prop="outline"/>
      <el-table-column label="图片" align="center" prop="img" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.img" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <!--      <el-table-column label="内容" align="center" prop="content"/>-->
      <el-table-column label="负责人" align="center" prop="responsiblePerson"/>
      <el-table-column label="活动开始时间" align="center" prop="activityStartTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.activityStartTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动结束时间" align="center" prop="activityEndTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.activityEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="活动地点" align="center" prop="activityPlace"/>
      <el-table-column label="报名开始时间" align="center" prop="startTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="报名截止时间" align="center" prop="endTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="人数上限" align="center" prop="upperLimit">
        <template #default="scope">
          <span>{{ scope.row.upperLimit==0?"不限人数":scope.row.upperLimit }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动状态" align="center" prop="releaseStatus">
        <template #default="scope">
          <el-tag :type="scope.row.releaseStatus ? scope.row.activityEndTime>new Date()?'warning':'success' : 'danger'">
            {{
              scope.row.releaseStatus ? scope.row.activityEndTime > new Date() ? '已结束' : '已发布' : '未发布'
            }}
          </el-tag>
        </template>
      </el-table-column>
      <!--      <el-table-column label="备注信息" align="center" prop="remark"/>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="200" fixed="right">
        <template #default="scope">
          <template v-if="scope.row.releaseStatus">
            <el-button type="primary" link icon="View" @click="handleView(scope.row)">查看</el-button>
            <el-button link type="danger" icon="Edit" @click="handleCancelRelease(scope.row)"> 取消发布</el-button>
            <el-button type="success" link icon="Download" @click="exportRegistrationRecords(scope.row)">导出报名数据
            </el-button>
          </template>
          <template v-if="!scope.row.releaseStatus">
            <el-button link type="primary" icon="Promotion" @click="handleRelease(scope.row)"> 发布</el-button>
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                       v-hasPermi="['system:activity:edit']">修改
            </el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                       v-hasPermi="['system:activity:remove']">删除
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改校园活动对话框 -->
    <el-dialog @close="close" :title="title" v-model="open" width="1200px" append-to-body>
      <el-form ref="activityRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="标题" prop="title">
          <el-input :disabled="view" maxlength="100" v-model="form.title" placeholder="请输入标题"/>
        </el-form-item>
        <el-form-item label="概要" prop="outline">
          <el-input :disabled="view" maxlength="200" type="textarea" v-model="form.outline" placeholder="请输入概要"/>
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="图片" prop="img">
              <image-upload v-if="!view" :limit="1" v-model="form.img"/>
              <image-preview v-if="view" :src="form.img" :width="500" :height="200"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="活动详情">
              <qr-code v-if="view&&form.id!==''" :text="baseURL+'/#/pages/activity/details?id='+form.id"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="活动详情">
              <qr-code v-if="view&&form.id!==''" :text="baseURL+'/#/pages/activity/details?id='+form.id"/>
            </el-form-item>
          </el-col>

        </el-row>

        <el-form-item label="内容">
          <editor v-if="!view" v-model="form.content" :min-height="300"/>
          <div v-if="view" v-html="form.content"></div>
        </el-form-item>
        <el-form-item label="活动地点" prop="activityPlace">
          <el-input :disabled="view" v-model="form.activityPlace" placeholder="请输入活动地点"/>
        </el-form-item>
        <el-row>
          <el-col :span="8">
            <el-form-item label="活动开始时间" prop="activityStartTime">
              <el-date-picker clearable
                              :disabled="view"
                              style="width: 100%"
                              v-model="form.activityStartTime"
                              type="datetime"
                              value-format="YYYY-MM-DD HH:mm:ss"
                              placeholder="请选择活动开始时间">
              </el-date-picker>
              <!--              <el-date-picker-->
              <!--                  v-model="value1"-->
              <!--                  type="datetime"-->
              <!--                  :disabled="view"-->
              <!--                  style="width: 100%"-->
              <!--                  v-model="form.activityStartTime"-->
              <!--                  placeholder="Select date and time"-->
              <!--              />-->
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="活动结束时间" prop="activityEndTime">
              <el-date-picker clearable
                              :disabled="view"
                              style="width: 100%"
                              v-model="form.activityEndTime"
                              type="datetime"
                              value-format="YYYY-MM-DD HH:mm:ss"
                              placeholder="请选择活动结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="负责人" prop="responsiblePerson">
              <el-input :disabled="view" v-model="form.responsiblePerson" placeholder="请输入负责人"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="报名开始时间" prop="startTime">
              <el-date-picker clearable
                              :disabled="view"
                              style="width: 100%"
                              v-model="form.startTime"
                              type="datetime"
                              value-format="YYYY-MM-DD HH:mm:ss"
                              placeholder="请选择报名开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="报名截止时间" prop="endTime">
              <el-date-picker clearable
                              :disabled="view"
                              style="width: 100%"
                              v-model="form.endTime"
                              type="datetime"
                              value-format="YYYY-MM-DD HH:mm:ss"
                              placeholder="请选择报名截止时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="人数上限" prop="upperLimit">
              <el-input :disabled="view" type="number" :min="0" v-model="form.upperLimit" placeholder="请输入人数上限"/>
            </el-form-item>
          </el-col>
        </el-row>


        <el-form-item label="备注信息" prop="remark">
          <el-input :disabled="view" maxlength="500" v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>

      </el-form>
      <template #footer v-if="!view">
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Activity">
import {
  listActivity,
  getActivity,
  delActivity,
  addActivity,
  updateActivity,
  releaseActivity,
  cancelReleaseActivity
} from "@/api/system/activity";
import QrCode from "@/components/qrcode.vue";
import QRCode from 'qrcode'
const {proxy} = getCurrentInstance();

const activityList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const view = ref(false);
const baseURL = ref(import.meta.env.VITE_MOBILE_URL);
const qrcodeDataURL = ref("");
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: null,
    outline: null,
    responsiblePerson: null,
  },

  rules: {
    title: [
      {required: true, message: "活动标题不能为空", trigger: "blur"}
    ],
    outline: [
      {required: true, message: "活动概要不能为空", trigger: "blur"}
    ],
    content: [
      {required: true, message: "活动内容不能为空", trigger: "blur"}
    ],
    activityStartTime: [
      // {required: true, message: "活动开始时间不能为空", trigger: "blur"},
      {validator: validateActivityStartTime, trigger: "change"}
    ],
    activityEndTime: [
      // {required: true, message: "活动结束时间不能为空", trigger: "blur"},
      {validator: validateActivityEndTime, trigger: "change"}
    ],
    activityPlace: [
      {required: true, message: "活动地点不能为空", trigger: "blur"}
    ],
    startTime: [
      // {required: true, message: "报名开始时间不能为空", trigger: "blur"},
      {validator: validateStartTime, trigger: "change"}
    ],
    endTime: [
      // {required: true, message: "报名截止时间不能为空", trigger: "blur"},
      {validator: validateEndTime, trigger: "change"}
    ],
    upperLimit: [
      {required: true, message: "人数上限不能为空", trigger: "blur"},
    ]
  }
});
const {queryParams, form, rules} = toRefs(data);

// 活动开始时间规则
function validateActivityStartTime(rule, value, callback) {
  if (value === null) {
    callback(new Error("活动开始时间不能为空"));
  } else if (value >= form.value.activityEndTime) {
    callback(new Error("活动开始时间不能大于活动结束时间"));
  } else if (value < form.value.startTime) {
    callback(new Error("活动开始时间不能小于报名开始时间"));
  } else {
    callback();
  }
}

// 活动结束时间规则
function validateActivityEndTime(rule, value, callback) {
  if (value > new Date()) {
    callback(new Error("活动结束时间不能小于当前时间"));
  }
  if (value === null) {
    callback(new Error("活动结束时间不能为空"));
  } else if (value <= form.value.activityStartTime) {
    callback(new Error("活动结束时间不能小于活动开始时间"));
  } else if (value < form.value.startTime) {
    callback(new Error("活动结束时间不能小于报名开始时间"));
  } else {
    callback();
  }
}

// 报名开始时间规则
function validateStartTime(rule, value, callback) {
  if (value === null) {
    callback(new Error("报名开始时间不能为空"));
  } else if (value >= form.value.endTime) {
    callback(new Error("报名开始时间不能大于报名截止时间"));
  } else if (value > form.value.activityStartTime) {
    callback(new Error("报名开始时间不能大于活动开始时间"));
  } else if (value > form.value.activityEndTime) {
    callback(new Error("报名开始时间不能大于活动结束时间"));
  } else {
    callback();
  }
}

// 报名截止时间规则
function validateEndTime(rule, value, callback) {
  console.log(value)
  console.log(form.value.startTime)
  console.log(form.value.activityEndTime)
  if (value === null) {
    callback(new Error("报名截止时间不能为空"));
  } else if (value <= form.value.startTime) {
    callback(new Error("报名截止时间不能小于报名开始时间"));
  } else if (value > form.value.activityEndTime) {
    callback(new Error("报名截止时间不能大于活动结束时间"));
  } else {
    callback();
  }
}


/** 查询校园活动列表 */
function getList() {
  loading.value = true;
  listActivity(queryParams.value).then(response => {
    activityList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function generateQRCode() {
  const canvas = this.$refs.qrcodeCanvas
  QRCode.toCanvas(canvas, this.text, error => {
    if (error) console.error(error)
  })
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    title: null,
    outline: null,
    img: null,
    content: null,
    responsiblePerson: null,
    activityStartTime: null,
    activityEndTime: null,
    activityPlace: null,
    startTime: null,
    endTime: null,
    upperLimit: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null,
    remark: null,
    delFlag: null
  };
  proxy.resetForm("activityRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加校园活动";
}


/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getActivity(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改校园活动";
  });
}

function handleView(row) {
  reset();
  const _id = row.id || ids.value
  getActivity(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "查看校园活动";
    view.value = true;
  });
}

function close() {
  view.value = false;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["activityRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateActivity(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addActivity(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除校园活动编号为"' + _ids + '"的数据项？').then(function () {
    return delActivity(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

function handleRelease(row) {
  proxy.$modal.confirm('是否发布校园活动[' + row.title + ']？').then(function () {
    return releaseActivity(row.id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("发布成功");
  }).catch(() => {
  });

}

function handleCancelRelease(row) {
  proxy.$modal.confirm('是否取消发布校园活动[' + row.title + ']？').then(function () {
    return cancelReleaseActivity(row.id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("取消发布成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/activity/export', {
    ...queryParams.value
  }, `activity_${new Date().getTime()}.xlsx`)
}

/**导出报名数据*/
function exportRegistrationRecords(row) {
  proxy.download('system/activity/export/enroll', {
    id: row.id
  }, `${row.title}_${new Date().getTime()}.xlsx`)
}

getList();
</script>
